#include <stdio.h>
#include "ESP_LOG.h"
#include "freertos/FreeRTOS.h"
#include "lvgl.h"
#include "nvs.h"
#include "nvs_flash.h"
#include "my_app.h"
#include "gui_guider.h"

#define TAG "ui_state_init"
#define STORAGE_WIFI_SWITCH "set_wifi_sw"
#define BOOL_WIFI_SWITCH "wifi_state"
#define STORAGE_TIME_SWITCH "set_time_sw"
#define BOOL_TIME_SWITCH "time_state"
/*读取nvs变量,判断掉电前开关部件的状态*/

void ui_read_val_init()
{

    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND)
    {
        // NVS出现错误，执行擦除
        ESP_ERROR_CHECK(nvs_flash_erase());
        // 重新尝试初始化
        ESP_ERROR_CHECK(nvs_flash_init());
    }
    wifi_switch_flag = read_wifi_sw_state(); // 读取nvs里wifi开关部件的状态

    SetDateTimeFlag = read_time_sw_state(); // 读取nvs里设置时间开关部件的状态
}
esp_err_t write_value_to_nvs(const char *namespace_name, const char *key, uint8_t value)
{
    // 初始化NVS
    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND)
    {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK(ret);

    // 打开NVS命名空间
    nvs_handle_t nvs_handle;
    ret = nvs_open(namespace_name, NVS_READWRITE, &nvs_handle);
    ESP_ERROR_CHECK(ret);

    // 写入bool型变量
    ret = nvs_set_u8(nvs_handle, key, value);
    ESP_ERROR_CHECK(ret);

    // 提交更改
    ret = nvs_commit(nvs_handle);
    ESP_ERROR_CHECK(ret);

    // 关闭NVS命名空间
    nvs_close(nvs_handle);
    return ret;
}

uint8_t read_value_from_nvs(const char *namespace_name, const char *key)
{
    // 初始化NVS
    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND)
    {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK(ret);

    // 打开NVS命名空间
    nvs_handle_t nvs_handle;
    ret = nvs_open(namespace_name, NVS_READWRITE, &nvs_handle);
    ESP_ERROR_CHECK(ret);

    // 读取u8变量
    uint8_t value;
    ret = nvs_get_u8(nvs_handle, key, &value);
    if (ret == ESP_ERR_NVS_NOT_FOUND)
    {
        // 如果键不存在，返回一个默认值
        value = false;
    }
    else
    {
        ESP_ERROR_CHECK(ret);
    }

    // 关闭NVS命名空间
    nvs_close(nvs_handle);

    return value;
}

/*读取wifi开关状态*/
bool read_wifi_sw_state(void)
{
    uint8_t value = read_value_from_nvs(STORAGE_WIFI_SWITCH, BOOL_WIFI_SWITCH);
    ESP_LOGI(TAG, "read_wifi_sw_state:%d", value);
    return value;
}
/*读取时间开关状态*/
bool read_time_sw_state(void)
{
    uint8_t value = read_value_from_nvs(STORAGE_TIME_SWITCH, BOOL_TIME_SWITCH);
    ESP_LOGI(TAG, "read_time_sw_state:%d", value);
    return value;
}
/*写入wifi开关状态*/
esp_err_t write_wifi_sw_state(bool state)
{
    esp_err_t res = write_value_to_nvs(STORAGE_WIFI_SWITCH, BOOL_WIFI_SWITCH, state);
    return res;
}
/*写入时间开关状态*/
esp_err_t write_time_sw_state(bool state)
{
    esp_err_t res = write_value_to_nvs(STORAGE_TIME_SWITCH, BOOL_TIME_SWITCH, state);
    return res;
}